package cn.blogger.controller;

import cn.blogger.base.BaseController;
import cn.blogger.entity.Result;
import cn.blogger.pojo.TBlog;

import cn.blogger.service.BlogService;
import cn.blogger.utils.Pager;
import com.alibaba.dubbo.config.annotation.Reference;

import com.sun.istack.Nullable;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@CrossOrigin
@RequestMapping("/blog")
public class BlogController extends BaseController {

    @Reference
    private BlogService blogService;

    //展示所有博客
    @GetMapping("/all.do")
    public Result all(){
//    public Result all(@RequestParam(value = "currentPage", defaultValue = 1 + "") String sCurrentPage,
//                        @RequestParam(value = "pageSize", defaultValue = 10 + "") String sPageSize){

//        int currentPage = Integer.parseInt(sCurrentPage);
//        int pageSize = Integer.parseInt(sPageSize);
//        List<TBlog> pagers = new ArrayList<>() ;
        String sql = "select * from t_blog";
        try {
            Pager<TBlog> pagers = blogService.findBySqlRerturnEntity(sql) ;
            System.out.println(pagers.toString());
            return new Result(true,"查询成功",pagers);
        }catch (Exception e){
            return new Result(false, "查询失败");
        }
    }

    //查询博客
    @PostMapping("/search.do")
    public Result search(@RequestParam(value = "title") @Nullable  String title,
                         @RequestParam(value = "author")@Nullable String author){
        Map<String,Object> map = new HashMap<>();
        map.put("title",title);
        map.put("author",author);
        try {
            Pager<TBlog> pagers = blogService.findByMap(map);
            return new Result(true,"查询成功",pagers);
        }catch (Exception e){
            return new Result(false, "新增标签失败");
        }
    }



    // 删除博客
    @DeleteMapping("/delete.do")
    public Result delete(@RequestParam(value = "bid",defaultValue = "0") int bid){
        try {
            blogService.deleteById(bid);
        }catch (Exception e){
            return new Result(false,"标签删除失败");
        }
        return new Result(true,"标签删除成功");
    }


    //新增博客
    @PostMapping("/add.do")
    public Result add(@RequestBody TBlog tBlog){
        try {
            blogService.insert(tBlog);

        }catch (Exception e){
            return new Result(false, "新增标签失败");
        }
        return new Result(false, "新增标签成功");
    }


    //更新博客
    @PutMapping("/update.do")
    public Result update(@RequestBody TBlog tBlog){
        try {
            blogService.update(tBlog);
        }catch (Exception e){
            return new Result(false,"标签更新失败");
        }
        return new Result(true,"标签更新成功");
    }




}
